package com.ruoyi.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.MealVerification;
import com.ruoyi.system.domain.dto.MealVerificationQueryDTO;
import com.ruoyi.system.domain.vo.MealVerificationDetailVO;
import com.ruoyi.system.domain.vo.MealVerificationResultVO;
import com.ruoyi.system.mapper.MealVerificationMapper;
import com.ruoyi.system.service.IMealVerificationService;

import com.ruoyi.system.domain.VerificationExportVO;
import com.ruoyi.system.domain.VerificationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * 核销管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-15
 */
@Service
public class MealVerificationServiceImpl implements IMealVerificationService {
    @Autowired
    private MealVerificationMapper mealVerificationMapper;

    /**
     * 查询核销管理
     *
     * @param id 核销管理主键
     * @return 核销管理
     */
    @Override
    public MealVerification selectMealVerificationById(Long id) {
        return mealVerificationMapper.selectMealVerificationById(id);
    }

    /**
     * 查询核销管理列表
     *
     * @param mealVerification 核销管理
     * @return 核销管理
     */
    @Override
    public List<MealVerification> selectMealVerificationList(MealVerification mealVerification) {
        return mealVerificationMapper.selectMealVerificationList(mealVerification);
    }

    /**
     * 新增核销管理
     *
     * @param mealVerification 核销管理
     * @return 结果
     */
    @Override
    public int insertMealVerification(MealVerification mealVerification) {
        return mealVerificationMapper.insertMealVerification(mealVerification);
    }

    /**
     * 修改核销管理
     *
     * @param mealVerification 核销管理
     * @return 结果
     */
    @Override
    public int updateMealVerification(MealVerification mealVerification) {
        return mealVerificationMapper.updateMealVerification(mealVerification);
    }

    /**
     * 根据员工ID和培训ID更新核销状态
     *
     * @param empId      员工ID
     * @param trainingId 培训ID
     * @param isVerified 核销状态
     * @return 结果
     */
    @Override
    public int updateVerificationStatusByEmpAndTraining(Long empId, Long trainingId, Integer isVerified) {
        return mealVerificationMapper.updateVerificationStatusByEmpAndTraining(empId, trainingId, isVerified);
    }

    /**
     * 批量删除核销管理
     *
     * @param ids 需要删除的核销管理主键
     * @return 结果
     */
    @Override
    public int deleteMealVerificationByIds(Long[] ids) {
        return mealVerificationMapper.deleteMealVerificationByIds(ids);
    }

    @Override
    public int deleteMealVerificationById(Long id) {
        return mealVerificationMapper.deleteMealVerificationById(id);
    }

    @Override
    public List<VerificationVO> selectVerificationVOList(VerificationVO verificationVO) {
        return mealVerificationMapper.selectVerificationVOList(verificationVO);
    }

    @Override
    public List<VerificationExportVO> selectVerificationExportVOList(VerificationVO verificationVO) {
        // 添加调试日志
        System.out.println("=== 核销导出数据查询开始 ===");
        System.out.println("查询参数: " + verificationVO);

        // 获取完整的 VerificationVO 数据
        List<VerificationVO> voList = mealVerificationMapper.selectVerificationVOList(verificationVO);

        System.out.println("查询到的原始数据条数: " + (voList != null ? voList.size() : 0));

        if (voList == null || voList.isEmpty()) {
            System.out.println("未查询到任何数据");
            return new ArrayList<>();
        }

        // 使用Map来去重，key为(培训名称+员工编号)
        Map<String, VerificationExportVO> exportMap = new LinkedHashMap<>();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        int seq = 1;
        for (VerificationVO vo : voList) {
            // 创建唯一标识符
            String key = vo.getTrainingName() + "_" + vo.getEmployeeNo();
            System.out.println("处理记录 - 唯一标识符: " + key + ", 员工姓名: " + vo.getEmployeeName() + ", 日期: " + vo.getMealDate() + ", 餐别: " + vo.getMealType());

            // 如果还没有这个员工的记录，创建新的
            if (!exportMap.containsKey(key)) {
                VerificationExportVO exportVO = new VerificationExportVO();
                exportVO.setSeq(seq++);
                exportVO.setTrainingName(vo.getTrainingName());
                exportVO.setEmployeeName(vo.getEmployeeName());
                exportVO.setEmployeeNo(vo.getEmployeeNo());
                exportVO.setDept(vo.getDepartment());
                exportVO.setPhone(vo.getPhone());
                exportVO.setEmail(vo.getEmail());
                exportVO.setStartDate(vo.getStartDate());
                exportVO.setEndDate(vo.getEndDate());

                // 设置培训时间
                if (vo.getStartDate() != null && vo.getEndDate() != null) {
                    exportVO.setTrainingTime(dateFormat.format(vo.getStartDate()) + "至" + dateFormat.format(vo.getEndDate()));
                }

                // 转换性别
                if (vo.getGender() != null) {
                    exportVO.setSex("1".equals(vo.getGender()) ? "男" : "0".equals(vo.getGender()) ? "女" : vo.getGender());
                }

                // 初始化核销情况Map
                exportVO.setDailyVerifications(new HashMap<>());

                exportMap.put(key, exportVO);
                System.out.println("创建新员工记录: " + key);
            }

            // 获取已存在的记录
            VerificationExportVO exportVO = exportMap.get(key);

            // 处理核销详情
            if (vo.getMealDate() != null && vo.getMealType() != null) {
                String dateStr = dateFormat.format(vo.getMealDate());

                // 获取或创建该日期的核销信息
                Map<String, String> mealInfo = exportVO.getDailyVerifications().get(dateStr);
                if (mealInfo == null) {
                    mealInfo = new HashMap<>();
                    exportVO.getDailyVerifications().put(dateStr, mealInfo);
                }

                // 设置午餐或晚餐的核销状态
                if (vo.getIsOrdered() != null) {
                    if (vo.getIsOrdered() == 0) {
                        mealInfo.put(vo.getMealType(), "未订餐");
                    } else {
                        // 修复：正确处理NULL值的情况
                        if (vo.getIsVerified() != null && vo.getIsVerified() == 1) {
                            mealInfo.put(vo.getMealType(), "已核销");
                        } else {
                            // 当isVerified为null或者0时，都表示未核销
                            mealInfo.put(vo.getMealType(), "未核销");
                        }
                    }
                } else {
                    mealInfo.put(vo.getMealType(), "未订餐");
                }
                System.out.println("更新核销信息 - 日期: " + dateStr + ", 餐别: " + vo.getMealType() + ", 状态: " + mealInfo.get(vo.getMealType()));
            }
        }

        // 转换为列表
        List<VerificationExportVO> result = new ArrayList<>(exportMap.values());
        System.out.println("最终导出数据条数: " + result.size());
        System.out.println("=== 核销导出数据查询结束 ===");
        return result;
    }

    /**
     * 查询核销表，计算核销占比
     * @return 统计结果:已核销、未核销、核销占比
     */
    @Override
    public MealVerificationResultVO calculateVerification(MealVerificationQueryDTO queryDTO) {

        if (queryDTO.getVerifyTime() == null) {
            // 默认当天
            queryDTO.setVerifyTime(new Date());
        }
        if (!StringUtils.hasText(queryDTO.getMealType())) {
            // 默认午餐
            queryDTO.setMealType("午餐");
        }

        // 查询数据
        List<MealVerificationDetailVO> verifiedDetails =
                mealVerificationMapper.selectVerifiedDetails(queryDTO);

        List<MealVerificationDetailVO> unverifiedDetails =
                mealVerificationMapper.selectUnverifiedDetails(queryDTO);

        // 计算统计值
        int verifiedCount = verifiedDetails.size();
        int unverifiedCount = unverifiedDetails.size();
        int total = verifiedCount + unverifiedCount;

        // 计算占比（保留两位小数）
        BigDecimal verifiedRatio = total > 0 ?
                BigDecimal.valueOf(verifiedCount * 100.0 / total)
                        .setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO;

        BigDecimal unverifiedRatio = total > 0 ?
                BigDecimal.valueOf(unverifiedCount * 100.0 / total)
                        .setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO;

        // 构建结果对象
        MealVerificationResultVO resultVO = new MealVerificationResultVO();
        resultVO.setVerifiedCount(verifiedCount);
        resultVO.setUnverifiedCount(unverifiedCount);
        resultVO.setVerifiedRatio(verifiedRatio);
        resultVO.setUnverifiedRatio(unverifiedRatio);
        resultVO.setVerifiedDetails(verifiedDetails);
        resultVO.setUnverifiedDetails(unverifiedDetails);

        return resultVO;
    }
    @Override
    public Map<String, List<VerificationExportVO>> selectGroupedExportData(VerificationVO verificationVO) {
        List<VerificationExportVO> exportList = selectVerificationExportVOList(verificationVO);

        // 按培训名称分组
        Map<String, List<VerificationExportVO>> groupedData = new LinkedHashMap<>();
        for (VerificationExportVO exportVO : exportList) {
            String trainingName = exportVO.getTrainingName();
            if (!groupedData.containsKey(trainingName)) {
                groupedData.put(trainingName, new ArrayList<>());
            }
            groupedData.get(trainingName).add(exportVO);
        }

        return groupedData;
    }

    @Override
    public List<VerificationVO> selectVerificationVoListByIds(List<Long> ids)
    {
        return mealVerificationMapper.selectVerificationVOListByIds(ids);
    }
}





